<?php

namespace App\Http\Controllers\API;

use App\Http\Requests\API\CreateAdminModelAPIRequest;
use App\Http\Requests\API\UpdateAdminModelAPIRequest;
use App\Models\AdminModel;
use App\Repositories\AdminModelRepository;
use Illuminate\Http\Request;
use App\Http\Controllers\AppBaseController;
use InfyOm\Generator\Criteria\LimitOffsetCriteria;
use Prettus\Repository\Criteria\RequestCriteria;
use Response;

/**
 * Class AdminModelController
 * @package App\Http\Controllers\API
 */

class AdminController extends AppBaseController
{
    /**
     * 参数验证规则
     * self::VALID_RULES[__FUNCTION__]
     */
    const VALID_RULES = [
        'login' => [
            'mobile' => 'required|min:11',
            'password' => 'required|min:6',
        ],

        'store' => [
            'username' => 'required|string',
            'mobile' => 'required|string|min:11',
            'password' => 'required|string',
        ],

        'updatePassword' => [
            'oldpassword' => 'required|string',
            'password'=>'required|min:6|confirmed',
            'password_confirmation' => 'required|min:6'
        ],
    ];

    /** @var  AdminModelRepository */
    private $adminModelRepository;

//    public function __construct(AdminModelRepository $adminModelRepo)
//    {
//        $this->adminModelRepository = $adminModelRepo;
//    }

    /**
     * 管理员登录接口
     * @return \Illuminate\Http\JsonResponse
     */
    public function login()
    {
        $mobile = $this->request->get('mobile', '');
        $password = $this->request->get('password', '');

        $input = $this->request->all();
        $this->validateInputParams('login', $input);

        $admin = AdminModel::where(['mobile' => $mobile, 'is_active' => 1])->first();
        if (empty($admin)) {
            return $this->error([], '管理员不存在或已被删除');
        }

        if (md5($password) != $admin->password) {
            return $this->error([], '密码错误');
        }

        $this->request->session()->put('user_id', $admin->id);

        return $this->success($admin->toArray(), '登录成功');
    }

    /**
     * 管理员登录接口
     * @return \Illuminate\Http\JsonResponse
     */
    public function logout()
    {
        $this->request->session()->flush();

        return $this->success([], '登出成功');
    }

    /**
     * @param AdminModelRepository $repository
     * @return \Illuminate\Http\JsonResponse
     */
    public function index(AdminModelRepository $repository)
    {
        $mobile = $this->request->get('', '');
        $password = $this->request->get('', '');
        $name = $this->request->get('name', '');


        $attr = ['mobile' => $mobile, 'pass'];
        $adminModels = $this->adminModelRepository->create($attr);

        return $this->sendResponse($adminModels->toArray(), 'Admin Models retrieved successfully');
    }

    /**
     *
     * Store a newly created AdminModel in storage.
     * POST /adminModels
     * @param CreateAdminModelAPIRequest $request
     *
     * @return Response
     */
    public function store(AdminModelRepository $repository)
    {
        $input = $this->request->all();
        $this->validateInputParams('store', $input);
        $password = $input['password'];
        $name = trim($input['username']);
        $mobile = trim($input['mobile']);

        if (strlen($password) < 6) {
            throwResponseException(1, '密码大于6位');
        }

        // 检查是否存在
        $admin = AdminModel::where(['mobile' => $mobile, 'is_active' => 1])->first();
        if (!empty($admin)) {
            throwResponseException(1, '该管理员已存在');
        }

        $input['password'] = md5($password);

        $adminModels = $repository->create($input);

        return $this->sendResponse($adminModels->toArray(), 'Admin Model saved successfully');
    }


    /**
     * @param TicketModelRepository $repo
     */
    public function search(AdminModelRepository $repo)
    {
        $input = $this->request->all();

        $searchOptions = $this->normalizeSearchOptions();
        $sortOptions = $this->normalizeSortOptions();
        $status = array_get($input, 'is_active', null);
        !isset($status) && $searchOptions['is_active'] = 1;

        $ret = $repo->search($searchOptions, $sortOptions);

        $lists = $ret['lists'];
        if (count($lists) == 0) {
            return $this->success(['lists' => []]);
        }

//        $lists = TicketDTOBuilderService::buildTickets($this->request->attributes->get('user_id'), $lists);
//        $ret['lists'] = $lists;

        return $this->success($ret);
    }

    /**
     * Display the specified AdminModel.
     * GET|HEAD /adminModels/{id}
     *
     * @param  int $id
     *
     * @return Response
     */
    public function show($id, AdminModelRepository $repository)
    {
        /** @var AdminModel $adminModel */
        $adminModel = $repository->findWithoutFail($id);

        if (empty($adminModel)) {
            return $this->sendError('管理员不存在');
        }

        return $this->sendResponse($adminModel->toArray(), '操作成功');
    }

    /**
     * Update the specified AdminModel in storage.
     * PUT/PATCH /adminModels/{id}
     *
     * @param  int $id
     * @param UpdateAdminModelAPIRequest $request
     *
     * @return Response
     */
    public function update($id, AdminModelRepository $adminModelRepository)
    {
        $input = $this->request->all();
        unset($input['_url']);

        /** @var AdminModel $adminModel */
        $adminModel = $adminModelRepository->findWithoutFail($id);

        if (empty($adminModel) || $adminModel->is_active == 0) {
            return $this->sendError('管理员不存在或已删除');
        }

        isset($input['password']) && $input['password'] = md5($input['password']);
        $adminModel = AdminModel::where('id', $id)->update($input);

        return $this->sendResponse([], '跟新管理员信息成功');
    }

    /**
     * Update the specified AdminModel in storage.
     * PUT/PATCH /adminModels/{id}
     *
     * @param  int $id
     * @param UpdateAdminModelAPIRequest $request
     *
     * @return Response
     */
    public function updatePassword($id, AdminModelRepository $adminModelRepository)
    {
        $userId = $this->request->session()->get('user_id');
        $input = $this->request->all();

        $this->validateInputParams('updatePassword', $input);
        unset($input['_url']);

        /** @var AdminModel $adminModel */
        $adminModel = $adminModelRepository->findWithoutFail($userId);

        if (empty($adminModel) || $adminModel->is_active == 0) {
            return $this->sendError('管理员不存在或已删除');
        }

        if ($adminModel->password != md5($input['oldpassword'])) {
            return $this->sendError('原始密码错误');
        }

        $adminModel->password = md5($input['password']);
        $adminModel->save();
        
        return $this->sendResponse([], '修改密码成功');
    }

    /**
     * Remove the specified AdminModel from storage.
     * DELETE /adminModels/{id}
     *
     * @param  int $id
     *
     */
    public function destroy($id, AdminModelRepository $adminModelRepository)
    {
        /** @var AdminModel $adminModel */
        $adminModel = $adminModelRepository->findWithoutFail($id);

        if (empty($adminModel) && $adminModel->is_active == 0) {
            return $this->sendError('该管理员不存在或已被删除');
        }


        $adminModel->is_active = 0;
        $adminModel->save();

        return $this->success([], '操作成功');
    }

    /**
     * Remove the specified AdminModel from storage.
     * DELETE /adminModels/{id}
     *
     * @param  int $id
     *
     */
    public function batchDestroy()
    {
        $ids = $this->request->get('ids');
        if (empty($ids)) {
            return $this->sendError('id不为空');
        }

        $ids = explode(',', $ids);
        AdminModel::whereIn('id', $ids)->update(['is_active' => 0]);

        return $this->success([], '操作成功');
    }
}
